#Boa:Dialog:Dialog1

import wx
import wx.calendar
import wx.grid
import datetime

import consultasBD
import utiles
from decimal import Decimal

ROJO = (255, 145, 145, 255)
VERDE = (145, 255, 145, 255)
AZUL = (145, 145, 255, 255)
BLANCO = (255, 255, 255, 255)
AMARILLO = (254, 248, 191, 255)
GRIS = ( 220, 220, 220, 255)
NEGRO = ( 0, 0, 0, 255)
VERDENEGRO = ( 47, 79, 79, 255)

def create(parent):
    return Dialog1(parent)

[wxID_DIALOG1, wxID_DIALOG1BUTTON1, wxID_DIALOG1BUTTON2, wxID_DIALOG1BUTTON3, 
 wxID_DIALOG1BUTTON4, wxID_DIALOG1COMBOBOX1, wxID_DIALOG1COMBOBOX2, 
 wxID_DIALOG1GRID1, wxID_DIALOG1STATICTEXT1, wxID_DIALOG1STATICTEXT2, 
] = [wx.NewId() for _init_ctrls in range(10)]

class Dialog1(wx.Dialog):
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Dialog.__init__(self, id=wxID_DIALOG1, name='', parent=prnt,
              pos=wx.Point(85, 30), size=wx.Size(760, 572),
              style=wx.DEFAULT_DIALOG_STYLE, title='Estadisticas Mensuales')
        self.SetClientSize(wx.Size(752, 545))

        self.staticText1 = wx.StaticText(id=wxID_DIALOG1STATICTEXT1,
              label='Anio', name='staticText1', parent=self, pos=wx.Point(8, 8),
              size=wx.Size(21, 13), style=0)

        self.comboBox1 = wx.ComboBox(choices=[], id=wxID_DIALOG1COMBOBOX1,
              name='comboBox1', parent=self, pos=wx.Point(8, 24),
              size=wx.Size(55, 21), style=0, value='')
        self.comboBox1.SetLabel('')

        self.staticText2 = wx.StaticText(id=wxID_DIALOG1STATICTEXT2,
              label='Mes', name='staticText2', parent=self, pos=wx.Point(64, 8),
              size=wx.Size(19, 13), style=0)

        self.comboBox2 = wx.ComboBox(choices=[], id=wxID_DIALOG1COMBOBOX2,
              name='comboBox2', parent=self, pos=wx.Point(64, 24),
              size=wx.Size(130, 21), style=0, value='')
        self.comboBox2.SetLabel('')

        self.button1 = wx.Button(id=wxID_DIALOG1BUTTON1, label='Procesar',
              name='button1', parent=self, pos=wx.Point(200, 24),
              size=wx.Size(75, 23), style=0)
        self.button1.Bind(wx.EVT_BUTTON, self.OnProcesar,
              id=wxID_DIALOG1BUTTON1)

        self.button3 = wx.Button(id=wxID_DIALOG1BUTTON3, label='Imprimir',
              name='button3', parent=self, pos=wx.Point(288, 24),
              size=wx.Size(75, 23), style=0)
        self.button3.Bind(wx.EVT_BUTTON, self.OnImprimir,
              id=wxID_DIALOG1BUTTON3)

        self.button4 = wx.Button(id=wxID_DIALOG1BUTTON4, label='Exportar',
              name='button4', parent=self, pos=wx.Point(376, 24),
              size=wx.Size(75, 23), style=0)
        self.button4.Bind(wx.EVT_BUTTON, self.OnExportar,
              id=wxID_DIALOG1BUTTON4)

        self.button2 = wx.Button(id=wxID_DIALOG1BUTTON2, label='Salir',
              name='button2', parent=self, pos=wx.Point(672, 24),
              size=wx.Size(75, 23), style=0)
        self.button2.Bind(wx.EVT_BUTTON, self.OnSalir, id=wxID_DIALOG1BUTTON2)

        self.grid1 = wx.grid.Grid(id=wxID_DIALOG1GRID1, name='grid1',
              parent=self, pos=wx.Point(8, 56), size=wx.Size(736, 480),
              style=0)
        self.grid1.Bind(wx.grid.EVT_GRID_CELL_CHANGE, self.OnGrid1Cambia)

    def __init__(self, parent):
        self._init_ctrls(parent)
        self.cargarCombos()
        self.crearGrilla()

    def OnSalir(self, event):
        self.Close()
        
    def cargarCombos(self):
        anioinicial = 2008
        anioactual = int(utiles.obtenerFecha("Y-m-d")[:4])+1
        for year in range(anioinicial, anioactual):
            self.comboBox1.Append(str(year))
        self.comboBox1.SetSelection(len(self.comboBox1.GetItems())-1)
        self.comboBox2.Append("Enero")
        self.comboBox2.Append("Febrero")
        self.comboBox2.Append("Marzo")
        self.comboBox2.Append("Abril")
        self.comboBox2.Append("Mayo")
        self.comboBox2.Append("Junio")
        self.comboBox2.Append("Julio")
        self.comboBox2.Append("Agosto")
        self.comboBox2.Append("Septiembre")
        self.comboBox2.Append("Octubre")
        self.comboBox2.Append("Noviembre")
        self.comboBox2.Append("Diciembre")
        self.comboBox2.SetSelection(datetime.date.today().month-1)
        self.comboBox1.SetEditable(False)
        self.comboBox2.SetEditable(False)

    def ajustarAnchoColumnas(self):
        for y in xrange(self.grid1.GetNumberCols()):
            self.grid1.AutoSizeColumn(y,True)

    def crearGrilla(self):
        #SASKA,PEATONAL,PARANA,CEMTRAL,TOTAL
        #0     1        2      3       4
        columnas = ['Estado de Ganancias y Perdidas',
                     'SASKA','PEATONAL','PARANA','CENTRAL','TOTAL']
        self.grid1.CreateGrid(25,len(columnas))
        for i, col in enumerate(columnas): 
            self.grid1.SetColLabelValue(i, col)

##        self.grid1.SetSelectionMode(wx.grid.Grid.wxGridSelectRows)
##        self.grid1.EnableEditing(False)
        self.grid1.Refresh()

        columna = ["VENTAS","INVENTARIO INICIAL","INVENTARIO FINAL",
                   "TRANSFERENCIAS DESDE OTRAS SUCURSALES",
                   "- Items transferidos (ingresos)",
                   "TRANSFERENCIAS A OTRAS SUCURSALES",
                   "- Items transferidos (egresos)",
                   "GASTOS GENERALES Y ADMINISTRATIVOS","UTILIDAD NETA",
                   "UTILIDAD DE VENTA (utilidades/venta)",
                   "MARGEN DE UTILIDAD BRUTA (venta-costo vta/venta)",
                   "COMPRAS TOTALES (solo en Central, sin IVA)",
                   "COMPRAS TOTALES (solo en Central, con IVA)",
                   "DEVOLUCIONES A PROVEEDORES",
                   "VENTAS (costo)",
                   "VENTAS (items)",
                   "Ventas segun precio de venta",
                   "Ventas segun precio de compra (costo)","Diferencia",
                   "Gastos Varios"]
        self.grid1.SetCellValue(0,0,columna[0]) #ventas $
        self.grid1.SetCellValue(1,0,columna[1]) #inventario inicial
        self.grid1.SetCellValue(2,0,columna[2]) #inventario final
        self.grid1.SetCellValue(3,0,columna[3]) #transf.desde
        self.grid1.SetCellValue(4,0,columna[4]) #items transf. ingresos
        self.grid1.SetCellValue(5,0,columna[5]) #transf.hacia
        self.grid1.SetCellValue(6,0,columna[6]) #items transf. egresos
        
        self.grid1.SetCellValue(9,0,columna[7]) #gtos.admin
        self.grid1.SetCellValue(10,0,columna[8]) #utilidad neta
        self.grid1.SetCellValue(11,0,columna[9]) #utilidad de venta
        self.grid1.SetCellValue(12,0,columna[10]) #margen utilidad bruta

        self.grid1.SetCellValue(14,0,columna[11]) #compras sin iva
        self.grid1.SetCellValue(15,0,columna[12]) #compras con iva
        self.grid1.SetCellValue(16,0,columna[13]) #devoluciones
        self.grid1.SetCellValue(17,0,columna[14]) #ventas (costo)
        self.grid1.SetCellValue(18,0,columna[15]) #ventas (items)
        
        self.grid1.SetCellValue(20,0,columna[16]) #ventas
        self.grid1.SetCellValue(21,0,columna[17]) #costo merc. vendida
        self.grid1.SetCellValue(22,0,columna[18]) #diferencia
        self.grid1.SetCellValue(23,0,columna[19]) #gastos varios

        self.grid1.SetCellValue(9,1,"0.00")
        self.grid1.SetCellValue(9,2,"0.00")
        self.grid1.SetCellValue(9,3,"0.00")
        self.grid1.SetCellValue(9,4,"0.00")
        self.grid1.SetCellValue(9,5,"0.00")

        self.grid1.SetCellValue(23,5,"0.00")

        self.grid1.SetCellBackgroundColour(9,1,GRIS)
        self.grid1.SetCellBackgroundColour(9,2,GRIS)
        self.grid1.SetCellBackgroundColour(9,3,GRIS)
        self.grid1.SetCellBackgroundColour(9,4,GRIS)
        
        self.grid1.SetCellAlignment(9,1, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.SetCellAlignment(9,2, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.SetCellAlignment(9,3, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.SetCellAlignment(9,4, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.SetCellAlignment(9,5, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)

        self.grid1.SetCellAlignment(23,5, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)

        self.ajustarAnchoColumnas()

    def rangoFecha(self):
        anio = self.comboBox1.GetLabel()
        mes = str(self.comboBox2.GetSelection()+1)
        if len(mes)<2: mes = "0"+mes
        fechaInicio = anio+"-"+mes+"-01"
        fechaFin = anio+"-"+mes+"-31"

        mesactual = self.comboBox2.GetSelection()+1
        mesanterior = mesactual-1
        anio = self.comboBox1.GetLabel()
        anioanterior = anio
        mesactual = str(mesactual)
        if len(mesactual)<2: mesactual = "0"+mesactual
        if mesanterior<1:
            mesanterior = 12
            anioanterior = int(anio)-1
            anioanterior = str(anioanterior)
        mesanterior = str(mesanterior)
        if len(mesanterior)<2: mesanterior = "0"+mesanterior
        mesactual = anio+"-"+mesactual
        mesanterior = anioanterior+"-"+mesanterior
        return fechaInicio,fechaFin,mesactual,mesanterior

    def totalizador(self):
        for fil in xrange(7):
            subtotal = Decimal("0.00")
            for col in xrange(4):
                aux = self.grid1.GetCellValue(fil,col+1)
                try:
                    aux = Decimal(aux).quantize(Decimal("0.10"))
                except:
                    aux = Decimal("0.00")
                subtotal+= aux
            self.grid1.SetCellValue(fil,5,str(subtotal))
            self.grid1.SetCellAlignment(fil,5, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        for fil in xrange(5):
            subtotal = Decimal("0.00")
            for col in xrange(4):
                aux = self.grid1.GetCellValue(fil+14,col+1)
                try:
                    aux = Decimal(aux).quantize(Decimal("0.10"))
                except:
                    aux = Decimal("0.00")
                subtotal+= aux
            self.grid1.SetCellValue(fil+14,5,str(subtotal))
            self.grid1.SetCellAlignment(fil+14,5, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        for col in xrange(5):
            ventas = self.grid1.GetCellValue(0,col+1)
            inicial = self.grid1.GetCellValue(1,col+1)
            final = self.grid1.GetCellValue(2,col+1)
            egresos = self.grid1.GetCellValue(3,col+1)
            ingresos = self.grid1.GetCellValue(5,col+1)
            try:
                ventas = Decimal(ventas).quantize(Decimal("0.10"))
            except:
                ventas = Decimal("0.00")
            try:
                inicial = Decimal(inicial).quantize(Decimal("0.10"))
            except:
                inicial = Decimal("0.00")
            try:
                final = Decimal(final).quantize(Decimal("0.10"))
            except:
                final = Decimal("0.00")
            try:
                egresos = Decimal(egresos).quantize(Decimal("0.10"))
            except:
                egresos = Decimal("0.00")
            try:
                ingresos = Decimal(ingresos).quantize(Decimal("0.10"))
            except:
                ingresos = Decimal("0.00")
            total = ventas-inicial+final-egresos-ingresos
            self.grid1.SetCellValue(7,col+1,str(total))
            self.grid1.SetCellAlignment(7,col+1, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            
    def OnProcesar(self, event):
        self.grid1.Bind(wx.grid.EVT_GRID_CELL_CHANGE, None)

        fechaInicial,fechaFinal,mesactual,mesanterior = self.rangoFecha()
        datosActual = {}
        datosPasado = {}
        for sucursal in xrange(4):
            r1 = "SELECT * FROM estadisticasmensuales "
            r2 = "WHERE sucursal='"+str(sucursal+1)+"' AND fecha LIKE '%"+mesactual+"%' "
            r3 = "ORDER BY fecha DESC, id DESC LIMIT 1 "
            sql = r1+r2+r3
            resultado = consultasBD.ordenCrudaDict(sql)
            try:
                datosActual[sucursal+1] = resultado[0]
            except:
                datosActual[sucursal+1] = {}
            r1 = "SELECT * FROM estadisticasmensuales "
            r2 = "WHERE sucursal='"+str(sucursal+1)+"' AND fecha LIKE '%"+mesanterior+"%' "
            r3 = "ORDER BY fecha DESC, id DESC LIMIT 1 "
            sql = r1+r2+r3
            resultado = consultasBD.ordenCrudaDict(sql)
            try:
                datosPasado[sucursal+1] = resultado[0]
            except:
                datosPasado[sucursal+1] = {}
        
        for sucursal in xrange(4):
            suc = sucursal+1
            datos = datosActual[suc]

            if suc == 1: col = 4
            elif suc == 2: col = 3
            elif suc == 3: col = 1
            else: col = 2
            
            try:
                stkInicialP = str(datosPasado[suc]["stckPcompra"])
            except:
                stkInicialP = "0.00"
            try:
                ventas = str(datos["vdoSPVta"])
                stkFinalP = str(datos["stckPcompra"])
                transfDesdeItems = str(datos["transfRecibidas"])
                transfDesde = str(datos["itCtoTfRecibido"])
                transfDesde = Decimal(transfDesde).quantize(Decimal("0.10"))
                transfDesde = str(transfDesde)
                transfHaciaItems = str(datos["transfEnviadas"])
                transfHacia = str(datos["itCtoTfEnviado"])
                transfHacia = Decimal(transfHacia).quantize(Decimal("0.10"))
                transfHacia = str(transfHacia)
                comprasTotalCIVA = str(datos["mtoComTotal"])
                comprasTotalSIVA = str(datos["mtoComCosto"])
                devoluciones = str(datos["mtoDev"])
                ventasCosto = str(datos["vdoCosto"])
                ventasItems = str(datos["vdoItems"])
            except:
                ventas = stkFinalP = transfDesde = "0.00"
                transfDesdeItems = transfHacia = transfHaciaItems = "0.00"
                comprasTotalCIVA = comprasTotalSIVA = devoluciones = "0.00"
                ventasCosto = ventasItems = "0.00"
            
            self.grid1.SetCellValue(0,col,ventas)
            self.grid1.SetCellValue(1,col,stkInicialP)
            self.grid1.SetCellValue(2,col,stkFinalP)
            self.grid1.SetCellValue(3,col,transfDesde)
            self.grid1.SetCellValue(4,col,transfDesdeItems)
            self.grid1.SetCellValue(5,col,transfHacia)
            self.grid1.SetCellValue(6,col,transfHaciaItems)
            self.grid1.SetCellValue(14,col,comprasTotalSIVA)
            self.grid1.SetCellValue(15,col,comprasTotalCIVA)
            self.grid1.SetCellValue(16,col,devoluciones)
            self.grid1.SetCellValue(17,col,ventasCosto)
            self.grid1.SetCellValue(18,col,ventasItems)
            
            self.grid1.SetCellAlignment(0,col, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(1,col, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(2,col, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(3,col, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(4,col, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(5,col, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(6,col, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(14,col, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(15,col, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(16,col, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(17,col, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(18,col, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)

        self.totalizador()

        ventasPrecioVta = self.grid1.GetCellValue(0,5)
        self.grid1.SetCellValue(20,5,ventasPrecioVta)
        self.grid1.SetCellAlignment(20,5, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        ventasPrecioCto = self.grid1.GetCellValue(17,5)
        self.grid1.SetCellValue(21,5,ventasPrecioCto)
        self.grid1.SetCellAlignment(21,5, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        try:
            ventasPrecioVta = Decimal(ventasPrecioVta).quantize(Decimal("0.10"))
        except:
            ventasPrecioVta = Decimal("0.00")
        try:
            ventasPrecioCto = Decimal(ventasPrecioCto).quantize(Decimal("0.10"))
        except:
            ventasPrecioCto = Decimal("0.00")
        diferencia = ventasPrecioVta - ventasPrecioCto
        self.grid1.SetCellValue(22,5,str(diferencia))
        self.grid1.SetCellAlignment(22,5, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)

        total = Decimal("0.00")
        for sucursal in xrange(4):
            suc = sucursal+1
            if suc == 1: col = 4
            elif suc == 2: col = 3
            elif suc == 3: col = 1
            else: col = 2
            
            aux1 = self.grid1.GetCellValue(7,col)
            aux2 = self.grid1.GetCellValue(9,col)
            try:
                aux1 = Decimal(aux1).quantize(Decimal("0.10"))
            except:
                aux1 = Decimal("0.00")
            try:
                aux2 = Decimal(aux2).quantize(Decimal("0.10"))
            except:
                aux2 = Decimal("0.00")
            utilidadNeta = aux1-aux2
            total+= utilidadNeta
            self.grid1.SetCellValue(10,col,str(utilidadNeta))
            self.grid1.SetCellAlignment(10,col, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.SetCellValue(10,5,str(total))
        self.grid1.SetCellAlignment(10,5, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        
        try:
            utilidadDeVenta = (total/ventasPrecioVta).quantize(Decimal("0.10"))
        except:
            utilidadDeVenta = Decimal("0.00")
        self.grid1.SetCellValue(11,5,str(utilidadDeVenta))
        self.grid1.SetCellAlignment(11,5, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)

        try:
            margenUtilidadBruta = (ventasPrecioVta/ventasPrecioVta).quantize(Decimal("0.10"))
        except:
            margenUtilidadBruta = Decimal("0.00")
        self.grid1.SetCellValue(12,5,str(margenUtilidadBruta))
        self.grid1.SetCellAlignment(12,5, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)

        self.ajustarAnchoColumnas()
        self.grid1.Bind(wx.grid.EVT_GRID_CELL_CHANGE, self.OnGrid1Cambia)

    def OnGrid1Cambia(self, event):
        fil = self.grid1.GetGridCursorRow()
        col = self.grid1.GetGridCursorCol()
        celda = self.grid1.GetCellValue(fil,col)
        if fil!=9: return
        if col not in [1,2,3,4]: return

        self.grid1.Bind(wx.grid.EVT_GRID_CELL_CHANGE, None)
        try:
            aux1 = Decimal(celda).quantize(Decimal("0.10"))
        except:
            aux1 = Decimal("0.00")
        
        self.grid1.SetCellValue(fil,col,str(aux1))
        self.grid1.SetCellAlignment(fil,col, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        total = Decimal("0.00")
        for columna in xrange(4):
            aux2 = Decimal(self.grid1.GetCellValue(fil,columna+1))
            total+= aux2
        self.grid1.SetCellValue(fil,5,str(total))
        self.grid1.SetCellAlignment(fil,5, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.SetCellValue(23,5,str(total))
        self.grid1.SetCellAlignment(23,5, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        
        aux3 = self.grid1.GetCellValue(22,5)
        try:
            aux3 = Decimal(aux3)
        except:
            aux3 = Decimal("0.00")
        aux4 = self.grid1.GetCellValue(23,5)
        aux4 = Decimal(aux4)
        try:
            aux4 = Decimal(aux4)
        except:
            aux4 = Decimal("0.00")
        diferencia = aux3-aux4
        self.grid1.SetCellValue(24,5,str(diferencia))
        self.grid1.SetCellAlignment(24,5, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        
        self.grid1.Bind(wx.grid.EVT_GRID_CELL_CHANGE, self.OnGrid1Cambia)

    def OnImprimir(self, event):
        print "Imprimir"

        f=open("c:\\erpsussan.doc\\reporte-BalanceFinanciero.html","w")
        numeroPagina = 1
        nrosuc,nombresuc = utiles.datosSucursal()
        
        totalItemPorPagina = 55
        totalPaginas = int(self.grid1.GetNumberRows()-1) / totalItemPorPagina 
        totalPaginas+= 1

        def encabezadoPagina(texto):
            fecha = utiles.getfechaTime()

            a = '<table width="100%" cellspacing="0" border="0">\n'
            a+= '<tr>\n'
            a+= '<td valign="center" align="left" width="33%">'
            a+= 'SUSSAN BOUTIQUE<br>Balance Financiero'
            a+= '<br></td>\n<td valign="center" align="left" width="34%">'
            a+= '<br>'
            a+= '</td>\n'
            a+= '<td valign="center" align="right" width="33%">'+fecha
            a+= '<br>P&aacute;gina '+str(numeroPagina)+' / '+str(totalPaginas)+'</td>\n'
            a+= '</tr>\n'
            a+= '</table>\n'
            texto+= a
            return texto
        
        def encabezadoTabla(texto):
        #SASKA,PEATONAL,PARANA,CEMTRAL,TOTAL
        #0     1        2      3       4
            a = '<hr>'

            a+= '<table width="100%" cellspacing="1" border="0"> \n'
            a+= '<tr>\n'
            a+= '<td valign="top" align="left"></td> \n'
            a+= '<td valign="top" align="right">SASKA</td> \n'
            a+= '<td valign="top" align="right">PEATONAL</td> \n'
            a+= '<td valign="top" align="right">PARANA</td> \n'
            a+= '<td valign="top" align="right">CENTRAL</td> \n'
            a+= '<td valign="top" align="right">Total</td> \n'
            a+= '</tr> \n'
#            a+= '</table>\n'
            a+= '<tr>\n'
            a+= '<td colspan="6"><hr></td>\n'
            a+= '</tr>\n'
            texto+= a
            return texto
        
        cadena = '<?xml version="1.0" encoding="utf-8" ?> \n'
        cadena+= '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> \n'
        cadena+= '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> \n'
        cadena+= '<head> \n'
        cadena+= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> \n'
        cadena+= '<meta name="generator" content="Docutils 0.4.1: http://docutils.sourceforge.net/" /> \n'
        cadena+= '<title>Sussan Boutique</title> \n'
        cadena+= '</head> \n'
        cadena+= '<body> \n'

        cadena = encabezadoPagina(cadena)
        cadena = encabezadoTabla(cadena)
        f.write(cadena)

        renglon = 0
        for i in xrange(self.grid1.GetNumberRows()-1):
        #descripcion,SASKA,PEATONAL,PARANA,CEMTRAL,TOTAL
        #0           1     2        3      4       5
            descripcion = self.grid1.GetCellValue(i,0)
            if descripcion == "": descripcion = "&nbsp;"
            saska = self.grid1.GetCellValue(i,1)
            if saska == "": saska = "&nbsp;"
            peatonal = self.grid1.GetCellValue(i,2)
            if peatonal == "": peatonal = "&nbsp;"
            parana = self.grid1.GetCellValue(i,3)
            if parana == "": parana = "&nbsp;"
            central = self.grid1.GetCellValue(i,4)
            if central == "": central = "&nbsp;"
            total = self.grid1.GetCellValue(i,5)
            if total == "": total = "&nbsp;"
            
            cadena = '<tr> \n'
            cadena+= '<td valign="top" align="left">'+descripcion+'</td> \n'
            cadena+= '<td valign="top" align="right">'+saska+'</td> \n'
            cadena+= '<td valign="top" align="right">'+peatonal+'</td> \n'
            cadena+= '<td valign="top" align="right">'+parana+'</td> \n'
            cadena+= '<td valign="top" align="right">'+central+'</td> \n'
            cadena+= '<td valign="top" align="right">'+total+'</td> \n'
            cadena+= '</tr>\n'
            f.write(cadena)
            
            renglon+= 1
            
            if renglon == totalItemPorPagina :
                f.write("</table><!-- salto de pagina -->\n")
                f.write("<p STYLE='page-break-after: always;'></p>\n")                
                renglon = 0
                numeroPagina+= 1
                cadena = encabezadoPagina("")
                cadena = encabezadoTabla(cadena)
                f.write(cadena)

        tama = '"1"'
            
        cadena = '</table>\n'
        f.write(cadena)
        f.close()

        import os
        os.system("taskkill /IM firefox.exe /F")
        os.system("c:\\explorer.lnk c:\\erpsussan.doc\\reporte-BalanceFinanciero.html")

    def OnExportar(self, event):
        fecha = utiles.obtenerFecha("Y-m-d h:m:s")
        fecha = fecha.replace("-","")
        fecha = fecha.replace(" ","")
        fecha = fecha.replace(":","")
        dir = "c:\\erpsussan.doc\\"
        archivo = "balanceFinanciero-"+fecha+".cvs"
        nombre = dir+archivo
        f = open(nombre,"w")
        f.write("Estado de Ganancias y Perdidas;SASKA;PEATONAL;PARANA;CENTRAL;TOTAL\n")
        for fil in xrange(self.grid1.GetNumberRows()):
            cadena = ""
            for col in xrange(self.grid1.GetNumberCols()):
                celda = self.grid1.GetCellValue(fil,col)
                celda = celda.replace(".",",")
                cadena+= celda+";"
            f.write(cadena[:-1]+"\n")
        f.close()
        utiles.mensaje(None,"Exportado en "+dir+"\nen el archivo de nombre\n"+archivo)

